#!/bin/sh
#
# This script generates a project-wide version identifier for use by
# the `elftc_version()' API.

#
# Defaults.
#
branch="HEAD"
buildhost=`uname -s`
elftcname="elftoolchain"
options="b:e:h:o:t:"
top=""
versionfile="elftc_version.c"
progname=`basename ${0}`

usage()
{
    exec >&2

    # Print a message, if supplied.
    if [ -n "${*}" ]; then echo "##${@}"; fi

    echo "Usage: ${progname} [options]"
    echo "	Generate a toolchain-wide version number"
    echo "	-b BRANCH      Set the branch name [default: ${branch}]."
    echo "	-e PROJECTNAME Set the project name [default: ${elftcname}]."
    echo "	-h HOSTOS      Set the build OS [default: ${buildhost}]."
    echo "	-o OUTPUT      Set the output file [default: ${versionfile}]."
    echo "	-t TOPDIR      Set the top-of-tree directory [required]."
    exit 1
}

#
# Parse options.
#
set -- `getopt ${options} "$@"`

[ ${?} -eq 0 ] || usage

for option in ${*}; do
    case ${option} in
	-b) branch="${2}";	shift 2;;
	-e) elftcname="${2}";	shift 2;;
	-h) buildhost="${2}";	shift 2;;
	-o) versionfile="${2}";	shift 2;;
	-t) top="${2}";		shift 2;;
	--) shift; break;;
    esac
done

[ -n "${top}" ] || usage

# Try to determine the tree version.
#
# - If using SVN, use the `svninfo' tool.
# - If using CVS, use the string `unknown'.
# - Otherwise use `git --describe'.

curdir=`pwd`
cd ${top} || usage "ERROR: Cannot change directory to \"${top}\"."

versionstring=""
if [ -d .svn ]; then
    versionstring="svn:"$(svnversion)
elif [ -d CVS ]; then
    versionstring="cvs:unknown"
else # Try Git
    versionstring="git:"$(git describe --all --dirty --long)

    if [ ${?} -ne 0 ]; then
	usage "Cannot determine tree version."
    fi
fi

cd ${curdir} || usage "Cannot change back to ${curdir}."

#
# Only replace the source file if its content has changed.
#
tmpfile=`mktemp ${TMPDIR:-/tmp}/MV.XXXXXXX`
trap "rm -f ${tmpfile};" 0 1 2 3 15

cat > ${tmpfile} <<EOF
/* WARNING: Generated by "${progname}". */

#include <sys/types.h>
#include <libelftc.h>

const char *
elftc_version(void)
{
	return "${elftcname} ${branch} ${buildhost} ${versionstring}";
}
EOF

if ! cmp -s ${tmpfile} ${versionfile}; then
    echo "@ ${progname}: building \"${versionfile}\"."
    cp ${tmpfile} ${versionfile} || exit ${?}
fi
